<?php
namespace app;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\RouteNotFoundException;
use think\Response;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * @access protected
     * @param  Exception $exception
     * @return Response
     */
    protected function convertExceptionToResponse(Exception $exception)
    {
        if($exception instanceof RouteNotFoundException){
            return redirect("/");
        }else {
            // 收集异常数据
            $data = [
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'msg' => $this->getMessage($exception),
                'code' => $this->getCode($exception)
            ];
            $response = Response::create($data, 'json');
            if ($exception instanceof HttpException) {
                $statusCode = $exception->getStatusCode();
                $response->header($exception->getHeaders());
            }
            if (!isset($statusCode)) {
                $statusCode = 200;
            }
            $response->code($statusCode);
            return $response;
        }
    }
}
